﻿using Microsoft.ManagementConsole.SnapIns.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.ManagementConsole.SnapIns.Integration
{
    public class ServiceIntegrationBase
    {
        #region Fields&Properties

        private string servicePath;

        private ISerialization serialization;

        #endregion

        #region Methds

        public ServiceIntegrationBase(string servicePath, ISerialization serialization)
        {
            this.servicePath = servicePath;
            this.serialization = serialization;
        }

        private string ServicePathCombine(string pathExtention)
        {
            var result = this.servicePath;

            if (!string.IsNullOrEmpty(this.servicePath) &&
                !string.IsNullOrEmpty(pathExtention))
            {
                if (servicePath.EndsWith("/"))
                {
                    result = string.Format("{0}{1}", servicePath, pathExtention);
                }
                else
                {
                    result = string.Format("{0}/{1}", servicePath, pathExtention);
                }
            }

            return result;
        }

        public TResponse CallMethod<TRequest, TResponse>(string serviceMethod, TRequest request)
        {
            TResponse result = default(TResponse);

            if (!string.IsNullOrEmpty(servicePath) &&
                serialization != null)
            {
                var serviceCombinePath = ServicePathCombine(serviceMethod);

                var serializeRequest = serialization.Serialize<TRequest>(request);

                var httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceCombinePath);

                var postData = serializeRequest;

                var data = Encoding.ASCII.GetBytes(postData);

                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                httpWebRequest.ContentLength = data.Length;

                using (var stream = httpWebRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }

                var response = (HttpWebResponse)httpWebRequest.GetResponse();

                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

                result = serialization.Deserialize<TResponse>(responseString);
            }

            return result;
        }

        #endregion

    }
}
